Vue.component("upload",{
    // 自定义属性
    props: ["url", "width", "height"],
    data(){
        return {
            path:null
        }
    },
    // 插槽 slot
    template:`
        <span @click="$refs.file.click()"
            style="border: 1px solid #ddd; display: inline-block; cursor: pointer">
            <img v-if="path" :src="path" style="object-fit: cover"
                :style="{ width:width , height: height}">
            <slot v-else>
                <span :style="{ width:width , height: height}"
                    style="display: flex; justify-content: center; align-items: center;
                        font-size: 3em; color: #999">
                +
                </span>
            </slot>
            <input type="file" ref="file" style="display: none"
                accept="image/*" @change="upload($event.target.files)">
        </span>
    `,
    created(){
        this.width = this.width || "150px";
        this.height = this.height || "200px";
        this.url = this.url || "upload/image";
    },
    methods:{
        upload(files){
            if(files.length==0){
                alert("请选择要上传的文件");
                return;
            }
            let fd = new FormData();
            fd.append("file", files[0]);
            axios.post(this.url, fd).then(res=>{
                if(res.data.code == 1){
                    this.path = res.data.data;
                }
            });
            this.$refs.file.value = "";
        }
    }
})